package cn.net.autocode.platform.config;

import cn.hutool.core.util.StrUtil;
import cn.net.autocode.core.utils.ClientIpUtils;
import cn.net.autocode.core.utils.JwtUtils;
import cn.net.autocode.core.utils.PasswordUtils;
import cn.net.autocode.core.utils.UserThreadLocalUtils;
import cn.net.autocode.platform.cache.AutoCacheUtil;
import cn.net.autocode.platform.constants.PlatformConstant;
import com.alibaba.fastjson2.JSONObject;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 拦截器
 *
 */

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    private final AutoCacheUtil cacheUtil;

    public LoginInterceptor(AutoCacheUtil cacheUtil) {
        this.cacheUtil = cacheUtil;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        String uri = request.getRequestURI();
        //清空线程池
        UserThreadLocalUtils.clear();
        UserThreadLocalUtils.setClientIp(ClientIpUtils.getIpAddr(request));
        String token = request.getHeader(PlatformConfig.tokenKey);
        String mobileToken = request.getHeader(PlatformConfig.mobileTokenKey);
        String checkPassword = request.getHeader("checkPassword");
        if (checkPassword != null) {
            checkPassword = checkPassword.trim();
        }

        if (mobileToken != null && !mobileToken.isBlank()) {
            String username = JwtUtils.getUsername(mobileToken);
            if (StrUtil.isBlank(username)) {
                this.invalidToken(response);
                return false;
            }

            JSONObject user = cacheUtil.getTokenUser(mobileToken, "Y");
            if (user == null) {
                this.invalidToken(response);
                return false;
            } else {
                if (checkPassword != null && !checkPassword.isBlank()) {
                    String password = user.getString("passwrd");
                    if (!PasswordUtils.checkpw(checkPassword, password)) {
                        this.invalidPassword(response);
                        return false;
                    }
                }
                UserThreadLocalUtils.put(user);
                UserThreadLocalUtils.setToken(mobileToken);
            }

        } else {
            if (StrUtil.isBlank(token)) {
                //跳转到登录页面
                response.sendRedirect(request.getContextPath() + PlatformConstant.MAIN_PATH);
                return false;
            }

            String username = JwtUtils.getUsername(token);
            if (StrUtil.isBlank(username)) {
                //跳转到登录页面
                response.sendRedirect(request.getContextPath() + PlatformConstant.FORLOGIN_PATH);
                return false;
            }

            JSONObject user = cacheUtil.getTokenUser(token, "N");
            if (user == null) {
                if (!uri.equals("/platform/logout")) {
                    this.invalidToken(response);
                    return false;
                }
            } else {
                if (checkPassword != null && !checkPassword.isBlank()) {
                    String password = user.getString("passwrd");
                    if (!PasswordUtils.checkpw(checkPassword, password)) {
                        this.invalidPassword(response);
                        return false;
                    }
                }
                UserThreadLocalUtils.put(user);
                UserThreadLocalUtils.setToken(token);
            }
        }

        return true;

    }


    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws IOException {
        int status = response.getStatus();
        if (status != 200) {
            String uri = request.getRequestURI();

            if (status == 404) {
                response.setCharacterEncoding("utf-8");
                //告诉浏览器，服务器发送的消息体的数据的编码
                response.setHeader("content-type", "text/html;charset=utf-8");
                JSONObject res = new JSONObject();
                res.put("code", 0);
                res.put("msg", uri + "地址错误");
                PrintWriter out = response.getWriter();
                out.append(res.toString());
            } else {
                System.out.println(handler.getClass().getName());
            }
        }
    }

    public void invalidToken(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        //告诉浏览器，服务器发送的消息体的数据的编码
        response.setHeader("content-type", "text/html;charset=utf-8");
        JSONObject res = new JSONObject();
        res.put("code", 7);
        res.put("msg", "token失效，请重新登录！");
        PrintWriter out = response.getWriter();
        out.append(res.toString());
    }

    public void invalidPassword(HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        //告诉浏览器，服务器发送的消息体的数据的编码
        response.setHeader("content-type", "text/html;charset=utf-8");
        JSONObject res = new JSONObject();
        res.put("code", 0);
        res.put("msg", "密码错误！");
        PrintWriter out = response.getWriter();
        out.append(res.toString());
    }

}
